package com.iss.card.view.runable;

import java.lang.ref.SoftReference;
import java.util.Iterator;
import java.util.Vector;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.LruCache;

import com.iss.card.common.ApplicationManager;
import com.iss.card.common.CommonValue;
import com.iss.card.webservice.WebServiceUtils;
/**
 * download pic.
 * @author issuser
 *
 */
public class DownPicHandler extends Handler{
	private static final String TAG = DownPicHandler.class.getSimpleName();
	private Vector<Runnable> mAllRunnable;
	private ImageCallback mImageCallback;
	private Vector<String> mLoadingUrl;
//	public HashMap<String, SoftReference<Bitmap>> mBitmapCache;
	
	public DownPicHandler() {
		super();
	}
	
	public DownPicHandler(ImageCallback icb) {
		super();
		mAllRunnable = new Vector<Runnable>();
		mLoadingUrl  = new Vector<String>();
//		mHashMapBitmap = new HashMap<String, SoftReference<Bitmap>>();
		mImageCallback = icb;
	}
	
	@Override
	public void handleMessage(Message msg) {
		// TODO Auto-generated method stub
		super.handleMessage(msg);
		ThreadInfo ti = (ThreadInfo) msg.obj;
//		Log.i(TAG,"handleMessage:" + ti.url);
		mImageCallback.imageLoaded(ti.bitmap, ti.url);
//		CommonValue.mHashMapBitmap.put(ti.url, new SoftReference<Bitmap>(ti.bitmap));
		removeCallbacks(ti.drb);
		mAllRunnable.remove(ti.drb);
		mLoadingUrl.remove(ti.url);
		ti = null;
	}

	/**
	 * start thread.
	 * @param url
	 */
	public void startThread(String url){
//		Log.i(TAG,"startThread:" + url);
		if(mLoadingUrl.contains(url)){
			return;
		}
		mLoadingUrl.add(url);
		DownRunnable drb = new DownRunnable();
		ThreadInfo ti= new ThreadInfo();
		ti.url = url;
		ti.drb = drb;
		mAllRunnable.add(drb);
		drb.setThreadInfo(ti);
		new Thread(drb).start();
	}
	
	/**
	 * remove cache.
	 */
	public void remove(){
		if(mAllRunnable.size() > 0){
			Iterator<Runnable> it = mAllRunnable.iterator();
			while (it.hasNext()) {
				removeCallbacks(it.next());
			}
		}
//		mLoadingUrl.clear();
//		mBitmapCache.clear();
	}
	
	/**
	 * define thread.
	 * @author issuser
	 *
	 */
	class DownRunnable implements Runnable{
		private ThreadInfo threadInfo;
		private void setThreadInfo(ThreadInfo threadInfo){
			this.threadInfo = threadInfo;
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Message msg = new Message();
			threadInfo.bitmap = WebServiceUtils.downLoadPic(threadInfo.url, ApplicationManager.SCREEN_WIDTH);
			msg.obj = threadInfo;
			sendMessage(msg);
		}
	}
	
	/**
	 * package info.
	 * @author issuser
	 *
	 */
	class ThreadInfo{
		String url;
		Bitmap bitmap;
		Runnable drb;
	}
	
	/**
	 * call back,update image.
	 * @author issuser
	 *
	 */
	public interface ImageCallback {
        public void imageLoaded(Bitmap imageBitmap, String imageUrl);
    }
}
